package cn.onesdream.app.api.controller;

import cn.onesdream.app.api.service.UserService;
import cn.onesdream.app.common.exception.ServiceException;
import cn.onesdream.app.common.util.MobSMSUtil;
import cn.onesdream.app.common.util.ResponseResult;
import cn.onesdream.app.dao.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
@Api(tags = "用户相关接口")
@RequestMapping("/api/app/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("通过id数组获取用户列表")
    @PostMapping("getUserList")
    public ResponseResult<List> getUserList(Integer[] userId){
        List<User> userList = userService.getUserList(userId);
        for (User user : userList) {
            user.setPassword(null);
        }
        return new ResponseResult<>(userList);
    }

    @ApiOperation("登陆失败回馈")
    @GetMapping("/loginFailure")
    public ResponseResult loginFailure() throws ServiceException {
        throw new ServiceException("用户信息未认证！");
    }

    @ApiOperation("用户名密码登陆")
    @PostMapping("/loginByPassword")
    public ResponseResult<User> loginByPassword(@RequestParam @Pattern(regexp = "^1(3([0-35-9]\\d|4[1-8])|4[14-9]\\d|5([0-35689]\\d|7[1-79])|66\\d|7[2-35-8]\\d|8\\d{2}|9[13589]\\d)\\d{7}$", message = "手机号格式错误！") String account, String password) throws ServiceException {
        User user = userService.loginByPassword(account, password);
        return new ResponseResult(user);
    }

    @ApiOperation("手机验证码登陆")
    @PostMapping("/loginByPhoneCode")
    public ResponseResult<User> loginByPhoneCode(@RequestParam @Pattern(regexp = "^1(3([0-35-9]\\d|4[1-8])|4[14-9]\\d|5([0-35689]\\d|7[1-79])|66\\d|7[2-35-8]\\d|8\\d{2}|9[13589]\\d)\\d{7}$", message = "手机号格式错误！") String phoneNum, String code) throws UnsupportedEncodingException, ServiceException {
        Boolean isVerify = MobSMSUtil.getVerifyResult(phoneNum, code);
        User user;
        if(isVerify){
            Boolean existByAccount = userService.isExistByAccount(phoneNum);
            String token = null;
            /**
             * 如果用户不存在，则自动注册为新用户
             */
            if(!existByAccount){
                userService.insertCommonUserByPhoneNum(phoneNum);
            }
            token = userService.createToken(phoneNum);
            user = userService.getUserByAccount(phoneNum);
            user.setPassword(null);
            user.setToken(token);
            return new ResponseResult(user);
        }
        throw new ServiceException("验证码不匹配！");
    }

    @ApiOperation("聊天网页")
    @GetMapping("/chat")
    public ModelAndView chat(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ModelAndView webSocket = new ModelAndView("webSocket");
        return webSocket;
    }

    @ApiOperation("修改密码")
    @PostMapping("/changePassword")
    public ResponseResult changePassword(@RequestParam @NotNull String newPassword){
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        userService.changePassword(account, newPassword);
        return new ResponseResult();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/changeUserInfo")
    public ResponseResult<User> changeUserInfo(
            String sex,
            String nickname,
            String mobile,
            String birthday,
            String signature,
            String userDescribe) throws ServiceException {
        String mobileRegexp = "^1(3([0-35-9]\\d|4[1-8])|4[14-9]\\d|5([0-35689]\\d|7[1-79])|66\\d|7[2-35-8]\\d|8\\d{2}|9[13589]\\d)\\d{7}$";
        String sexRegexp = "^男|女|未知$";
        String birthdayRegexp = "^(\\d{4}-\\d{2}-\\d{2})|(\\d+|(\\s&&[^\\f\\n\\r\\t\\v])*)$";
        if(mobile != null && !mobile.matches(mobileRegexp)){
            throw new ServiceException("手机号码格式不对！");
        }
        if(sex != null && !sex.matches(sexRegexp)){
            throw new ServiceException("性别格式不对！（男，女，未知）");
        }
        if(birthday != null && !birthday.matches(birthdayRegexp)){
            throw new ServiceException("生日格式不对！（yyyy-MM-dd）");
        }
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.changeUserInfo(account, sex, nickname, mobile, birthday, signature, userDescribe);
        return new ResponseResult(user);
    }

    @ApiOperation("修改用户头像")
    @PostMapping("/changeUserHead")
    public ResponseResult<User> chaneUserHead(MultipartFile file) throws ServiceException, IOException {
        if(file == null){
            throw new ServiceException("头像不能为空！");
        }
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.changeUserHead(name, file);
        return new ResponseResult(user);
    }

    @ApiOperation("通过token获取用户信息")
    @GetMapping("/getUserInfoByToken")
    public ResponseResult<User> getUserInfoByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        User user = userService.getUserByToken(token);
        user.setPassword(null);
        return new ResponseResult(user);
    }

    @ApiOperation("通过userId获取用户信息")
    @GetMapping("/{userId}")
    public ResponseResult<User> getUserById(@PathVariable("userId") @NotNull Integer userId){
        User user = userService.getUserById(userId);
        user.setPassword(null);
        return new ResponseResult<>(user);
    }

    @ApiOperation("获取用户详细信息")
    @GetMapping("/getRole")
    public ResponseResult getRole(){
        Object details = SecurityContextHolder.getContextHolderStrategy().getContext().getAuthentication().getPrincipal();
        return new ResponseResult(details);
    }




}
